package eleanor.ltd.isRealEstate.pages;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import eleanor.ltd.isRealEstate.annotations.BuyerAccess;
import eleanor.ltd.isRealEstate.dao.client.ClientDAO;
import eleanor.ltd.isRealEstate.dao.user.UserDAO;
import eleanor.ltd.isRealEstate.entities.client.Client;
import eleanor.ltd.isRealEstate.entities.user.User;
import eleanor.ltd.isRealEstate.model.MD5;

@BuyerAccess
public class Registration {

	@Property
	@SessionState(create = false)
	private User user;
	
	@Property
	@SessionState(create = false)
	private Client client;
	
	@Inject
	private UserDAO userDAO;
	
	@Inject
	private ClientDAO clientDAO;
	
	@Component
	private Form createForm;
	
	void onPrepareFromCreateForm() {
		user = new User();
		client = new Client();
	}
	
	@Log
	Object onSubmitFromCreateForm() {
		System.out.println("RADIIIIIIIIIII");
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		System.out.println(dateFormat.format(date));
		
		if(userDAO.findByUsername(user.getUsername()) == null) {
			user.setUsername(user.getUsername());
			user.setPassword(MD5.md5(user.getPassword()));
			user.setEmailAddress(client.getClientEmail());
			user.setDateCreated(date);
			user.setActiveOrNot("yes");
			
			userDAO.save(user);
			
			
			client.setName(client.getName());
			client.setSurname(client.getSurname());
			client.setAddress(client.getAddress());
			client.setPhoneOne(client.getPhoneOne());
			client.setPhoneTwo(client.getPhoneTwo());
			client.setClientEmail(client.getClientEmail());
			client.setUserID(user);
			
			clientDAO.save(client);
			return Index.class;
		} else {
			return Registration.class;
		}
	}
}

